using Single.Core.Service;
using Single.Sugar.Service;
using Single.Sys.Entity;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Text;

namespace Single.Sys.Service
{
    public class SysUserRoleService : BaseService<SysUserRole>
    {
        public List<SysUserRole> GetByUserId(long id)
        {
            return rep.AsQueryable().Includes(m => m.SysRole).Where(m => m.UserId.Equals(id)).ToList();
        }

        public virtual ServiceResult SetRole(long userId, List<SysUserRole> rows)
        {
            var olds = rep.AsQueryable().Where(m => m.UserId.Equals(userId)).ToList();

            var iList = new List<SysUserRole>();

            foreach (var row in rows)
            {
                if (!olds.Any(m => m.RoleId.Equals(row.RoleId)))
                {
                    iList.Add(new SysUserRole { UserId = userId, RoleId = row.RoleId });
                }
            }

            var dList = new List<SysUserRole>();

            olds.ForEach(m =>
            {
                if (!rows.Any(n => n.RoleId.Equals(m.RoleId))) { dList.Add(m); }
            });

            var result = tenant.UseTran(() =>
            {
                rep.InsertRange(iList); rep.Delete(dList);
            });

            return UnknownResult(result.IsSuccess);
        }
    }
}